package org.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.springboot.common.Result;
import org.example.springboot.entity.*;
import org.example.springboot.mapper.OrderMapper;
import org.example.springboot.mapper.ProductMapper;
import org.example.springboot.mapper.RefundMapper;
import org.example.springboot.mapper.UserMapper;
import org.example.springboot.mapper.LogisticsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

@Service
public class RefundService {
    private static final Logger LOGGER = LoggerFactory.getLogger(RefundService.class);

    @Autowired
    private RefundMapper refundMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogisticsMapper logisticsMapper;

    /**
     * 生成退款单号
     * 格式：R + 年月日时分秒 + 用户ID后4位 + 4位随机数
     * @param userId 用户ID
     * @return 退款单号
     */
    private String generateRefundNo(Long userId) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String timeStr = now.format(formatter);
        
        // 用户ID后4位，不足4位前面补0
        String userIdStr = String.format("%04d", userId % 10000);
        
        // 4位随机数
        Random random = new Random();
        String randomStr = String.format("%04d", random.nextInt(10000));
        
        // 组合退款单号
        return "R" + timeStr + userIdStr + randomStr;
    }

    /**
     * 申请退款
     * @param refund 退款信息
     * @return 操作结果
     */
    @Transactional
    public Result<?> applyRefund(Refund refund) {
        try {
            // 检查订单是否存在
            Order order = orderMapper.selectById(refund.getOrderId());
            if (order == null) {
                return Result.error("-1", "订单不存在");
            }
            
//            // 检查订单状态是否允许退款（已支付或已发货）
//            if (order.getStatus() != 1 && order.getStatus() != 2) {
//                return Result.error("-1", "当前订单状态不允许申请退款");
//            }
            
            // 检查是否已经存在退款申请
            LambdaQueryWrapper<Refund> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Refund::getOrderId, refund.getOrderId());
            if (refundMapper.selectCount(queryWrapper) > 0) {
                return Result.error("-1", "该订单已有退款申请，请勿重复提交");
            }
            
            // 设置退款信息
            refund.setRefundNo(generateRefundNo(refund.getUserId()));
            refund.setOrderNo(order.getOrderNo());
            refund.setStatus(0); // 0-申请中
            refund.setApplyTime(Timestamp.valueOf(LocalDateTime.now()));
            
            // 如果未设置退款金额，默认为订单总价
            if (refund.getRefundAmount() == null) {
                refund.setRefundAmount(order.getTotalPrice());
            }
            
            // 保存退款申请
            int result = refundMapper.insert(refund);
            if (result > 0) {
                LOGGER.info("申请退款成功，退款ID：{}，订单ID：{}", refund.getId(), refund.getOrderId());
                return Result.success(refund);
            }
            return Result.error("-1", "申请退款失败");
        } catch (Exception e) {
            LOGGER.error("申请退款失败：{}", e.getMessage());
            return Result.error("-1", "申请退款失败：" + e.getMessage());
        }
    }

    /**
     * 处理退款申请
     * @param id 退款ID
     * @param status 处理状态：1-同意，2-拒绝
     * @param merchantRemark 商家备注
     * @return 操作结果
     */
    @Transactional
    public Result<?> processRefund(Long id, Integer status, String merchantRemark) {
        try {
            Refund refund = refundMapper.selectById(id);
            if (refund == null) {
                return Result.error("-1", "退款申请不存在");
            }
            
            // 检查退款状态是否为申请中
            if (refund.getStatus() != 0) {
                return Result.error("-1", "该退款申请已处理，无法重复处理");
            }
            
            // 更新退款状态
            refund.setStatus(status); // 1-已同意，2-已拒绝
            refund.setMerchantRemark(merchantRemark);
            refund.setProcessTime(Timestamp.valueOf(LocalDateTime.now()));
            
            // 如果同意退款，则进入退款流程
            if (status == 1) {
                // 更新为退款中状态
                refund.setStatus(3); // 3-退款中
                
                // 这里可以调用支付平台的退款接口
                // 模拟退款成功
                refund.setStatus(4); // 4-已退款
                refund.setSuccessTime(Timestamp.valueOf(LocalDateTime.now()));
                
                // 更新订单状态
                Order order = orderMapper.selectById(refund.getOrderId());
                if (order != null) {
                    // 更新订单状态为已退款
                    order.setStatus(5); // 5-已退款
                    orderMapper.updateById(order);
                    
                    // 查询并更新物流状态
                    LambdaQueryWrapper<Logistics> logisticsQueryWrapper = new LambdaQueryWrapper<>();
                    logisticsQueryWrapper.eq(Logistics::getOrderId, order.getId());
                    Logistics logistics = logisticsMapper.selectOne(logisticsQueryWrapper);
                    if (logistics != null) {
                        logistics.setStatus(5); // 5-已退款
                        logistics.setLastUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
                        logisticsMapper.updateById(logistics);
                    }
                    
                    // 恢复商品库存
                    Product product = productMapper.selectById(order.getProductId());
                    if (product != null) {
                        product.setStock(product.getStock() + order.getQuantity());
                        if (product.getSalesCount() >= order.getQuantity()) {
                            product.setSalesCount(product.getSalesCount() - order.getQuantity());
                        }
                        productMapper.updateById(product);
                    }
                    //退款
                    if(order.getUserId()!=null){
                        User user = userMapper.selectById(order.getUserId());
                        user.setBalance(user.getBalance()+order.getTotalPrice().doubleValue());
                        userMapper.updateById(user);
                    }

                }
            }
            
            int result = refundMapper.updateById(refund);
            if (result > 0) {
                LOGGER.info("处理退款申请成功，退款ID：{}，处理结果：{}", id, status == 1 ? "同意" : "拒绝");
                return Result.success(refund);
            }
            return Result.error("-1", "处理退款申请失败");
        } catch (Exception e) {
            LOGGER.error("处理退款申请失败：{}", e.getMessage());
            return Result.error("-1", "处理退款申请失败：" + e.getMessage());
        }
    }

    /**
     * 获取退款详情
     * @param id 退款ID
     * @return 退款详情
     */
    public Result<?> getRefundById(Long id) {
        try {
            Refund refund = refundMapper.selectById(id);
            if (refund == null) {
                return Result.error("-1", "退款申请不存在");
            }
            
            // 填充关联信息
            Order order = orderMapper.selectById(refund.getOrderId());
            if (order != null) {
              order.setProduct(productMapper.selectById(order.getProductId()));
            }

            refund.setOrder(order);
            refund.setUser(userMapper.selectById(refund.getUserId()));

            
            return Result.success(refund);
        } catch (Exception e) {
            LOGGER.error("获取退款详情失败：{}", e.getMessage());
            return Result.error("-1", "获取退款详情失败：" + e.getMessage());
        }
    }

    /**
     * 获取订单的退款信息
     * @param orderId 订单ID
     * @return 退款信息
     */
    public Result<?> getRefundByOrderId(Long orderId) {
        try {
            LambdaQueryWrapper<Refund> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Refund::getOrderId, orderId);
            
            Refund refund = refundMapper.selectOne(queryWrapper);
            if (refund == null) {
                return Result.error("-1", "该订单暂无退款申请");
            }
            Order order = orderMapper.selectById(refund.getOrderId());
            if (order != null) {
                order.setProduct(productMapper.selectById(order.getProductId()));
            }
            // 填充关联信息
            refund.setOrder(order);
            refund.setUser(userMapper.selectById(refund.getUserId()));
            
            return Result.success(refund);
        } catch (Exception e) {
            LOGGER.error("获取订单退款信息失败：{}", e.getMessage());
            return Result.error("-1", "获取订单退款信息失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询退款列表
     * @param userId 用户ID
     * @param status 退款状态
     * @param currentPage 当前页
     * @param size 每页大小
     * @return 退款列表
     */
    public Result<?> getRefundsByPage(Long userId, Integer status, Integer currentPage, Integer size) {
        try {
            Page<Refund> page = new Page<>(currentPage, size);
            LambdaQueryWrapper<Refund> queryWrapper = new LambdaQueryWrapper<>();
            
            if (userId != null) {
                queryWrapper.eq(Refund::getUserId, userId);
            }
            
            if (status != null) {
                queryWrapper.eq(Refund::getStatus, status);
            }
            
            queryWrapper.orderByDesc(Refund::getCreatedAt);
            
            Page<Refund> result = refundMapper.selectPage(page, queryWrapper);
            
            // 填充关联信息
            result.getRecords().forEach(refund -> {
                refund.setOrder(orderMapper.selectById(refund.getOrderId()));
                refund.setUser(userMapper.selectById(refund.getUserId()));
            });
            
            return Result.success(result);
        } catch (Exception e) {
            LOGGER.error("分页查询退款列表失败：{}", e.getMessage());
            return Result.error("-1", "分页查询退款列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取待处理退款数量
     * @param merchantId 商户ID
     * @return 待处理退款数量
     */
    public Result<?> getPendingRefundCount(Long merchantId) {
        try {
            LambdaQueryWrapper<Refund> queryWrapper = new LambdaQueryWrapper<>();
            // 状态为0表示申请中，即待处理
            queryWrapper.eq(Refund::getStatus, 0);
            
            // 如果指定了商户ID，则需要关联订单表查询
            if (merchantId != null) {
                // 先查询该商户的所有订单ID
                LambdaQueryWrapper<Order> orderQueryWrapper = new LambdaQueryWrapper<>();
                orderQueryWrapper.select(Order::getId);
                // 修正：应该查询merchantId字段，而不是userId字段
                // 但由于Order实体中没有直接的merchantId字段，我们需要通过商品关联查询
                // 假设Product实体中有merchantId字段，或者通过其他方式关联
                List<Long> orderIds = orderMapper.selectOrderIdsByMerchantId(merchantId);
                
                // 如果商户没有订单，则直接返回0
                if (orderIds == null || orderIds.isEmpty()) {
                    return Result.success(0);
                }
                
                // 查询这些订单中有待处理退款的数量
                queryWrapper.in(Refund::getOrderId, orderIds);
            }
            
            Long count = refundMapper.selectCount(queryWrapper);
            LOGGER.info("查询待处理退款数量成功，商户ID：{}，数量：{}", merchantId, count);
            return Result.success(count);
        } catch (Exception e) {
            LOGGER.error("查询待处理退款数量失败：{}", e.getMessage());
            return Result.error("-1", "查询待处理退款数量失败：" + e.getMessage());
        }
    }
} 